package com.game.chat_room;

import com.game.tools.LogTool;
import lombok.SneakyThrows;

import java.util.Vector;

public class ChatThreadManager extends Thread {
    private ChatThreadManager() {
    }

    private static final ChatThreadManager Cm = new ChatThreadManager();

    public static ChatThreadManager getChartManager() {
        LogTool.outputLog("获取聊天连接线程管理器");
        return Cm;
    }

    public static Vector<ChatThread> ChatSocket_vector = new Vector<ChatThread>();
    public static Vector<ChatThread> ChatSocket_vector_delete = new Vector<ChatThread>();


    public void add(ChatThread cs) {
        ChatSocket_vector.add(cs);
    }

    public void publish(ChatThread cs, String msg) {
        LogTool.outputLog("推送信息，线程：" + cs.toString() + " 信息：" + msg);
        for (ChatThread csTemp : ChatSocket_vector) {
            if (!cs.equals(csTemp)) {
                csTemp.out(msg + "\n");
            }
        }

    }

    public static String seeChatSocket_vector(){
        return ChatSocket_vector.toString();
    }

    @SneakyThrows
    public void run(){
        /*
        管理器轮询
         */
        while (true){
            LogTool.outputLog("已连接：" + ChatSocket_vector.size());
            LogTool.outputLog(ChatSocket_vector.toString());

            sleep(1000 * 60);
            synchronized(this){
                for(ChatThread csTemp : ChatSocket_vector){
                    if(csTemp.isServerClose()){
                        if(csTemp.getRunning()){
                            LogTool.outputLog("线程停止:" + csTemp.toString());
                            csTemp.setRunning(false);
                        }else{
                            csTemp.delete();
                            ChatSocket_vector_delete.add(csTemp);
                        }
                    }
                }
            }

            /*
             * 线程回收
             */
            for(ChatThread chatThread : ChatSocket_vector_delete){
                ChatSocket_vector.remove(chatThread);
            }
            ChatSocket_vector_delete.clear();

        }
    }



}
